<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- ! 工具条组件 -->
      <PageTools :text="`共有${total}条数据`">
        <el-button
          type="danger"
          size="small"
          :disabled="!checkPermission('employees_export')"
          @click="exportAllData"
          >普通Excel导出所有数据</el-button
        >
        <el-button
          type="info"
          autofocus
          :disabled="
            multipleSelection.length === 0 ||
            !checkPermission('employees_export')
          "
          @click="exportCheckData"
          size="small"
          >复杂Excel导出部分数据</el-button
        >
        <el-button
          type="success"
          size="small"
          @click="$router.push('/import?type=user')"
          :disabled="!checkPermission('employees_import')"
          >Excel导入</el-button
        >
        <el-button
          type="primary"
          size="small"
          @click="$refs.addEmployees.dialogShow = true"
          :disabled="!checkPermission('employees_add')"
          >新增员工</el-button
        >
      </PageTools>
      <br />
      <!-- ! 表格组件 -->
      <el-card>
        <el-table
          :data="list"
          border
          @selection-change="multipleSelection = $event"
        >
          <el-table-column type="selection" sortable="" />
          <el-table-column
            type="index"
            width="100px"
            label="序号"
            sortable=""
          />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column prop="username" label="头像" sortable="">
            <template slot-scope="{ row }">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                style="height: 80px"
                :src="row.staffPhoto"
                @click="showCodeImg(row.staffPhoto)"
                alt=""
              />
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            :formatter="formatterEmployment"
            sortable=""
          />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable="">
            <template slot-scope="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="enableState"
            label="账户状态"
            sortable=""
          >
            <!-- 约定规则： 1启用  2禁用 -->
            <template slot-scope="{ row }">
              <el-tag type="success" v-if="row.enableState * 1 === 1"
                >启用</el-tag
              >
              <el-tag type="info" v-else>禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail/' + row.id)"
                :disabled="!checkPermission('employees_edit')"
                >查看</el-button
              >
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="setRoleOpen(row.id)"
                >角色</el-button
              >
              <el-button
                type="text"
                :disabled="!checkPermission('employees_del')"
                @click="delRow(row.id)"
                size="small"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <br />
        <!-- 分页组件 -->
        <el-pagination
          @size-change="sizeChange"
          @current-change="currentChange"
          :current-page.sync="queryData.page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="queryData.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
        >
        </el-pagination>
      </el-card>
    </div>
    <!-- ! 新增组件 -->
    <addEmployees ref="addEmployees" @updateList="initData" />
    <!-- ! 展示二维码弹框 -->
    <el-dialog :visible.sync="showCode" title="查看头像二维码">
      <!-- 展示二维码 -->
      <canvas ref="canvas"></canvas>
    </el-dialog>
    <!-- !使用你设置角色组件 -->
    <setRole ref="setRole" />
  </div>
</template>
<script>
import {
  delEmployeesApi,
  getEmployeesListApi,
  getEmployeesInfoApi,
} from "@/api/employees";
import EmployeeEnum from "@/api/constant/employees";
import addEmployees from "./components/addEmployees.vue";
import setRole from "./components/setRole.vue";
// webpack只要编译就会把 这个文件加载进入，不推荐这么做。原因是  Export2Excel 依赖资源太多
// import { export_json_to_excel } from "@/vendor/Export2Excel";
import { formatDate } from "@/filters";
import QRCode from "qrcode";
import list from "@/mixins/list";
export default {
  mixins: [list],
  name: "Employess",
  components: { addEmployees, setRole },
  data() {
    return {
      // 列表变量
      // list: [],
      queryData: {
        // page: 1,
        size: 10,
      },
      total: 0,
      hireType: EmployeeEnum.hireType,
      multipleSelection: [],
      showCode: false,
    };
  },
  created() {
    // this.initData();
    console.log("员工的created");
  },
  methods: {
    // 【列表功能】 获取列表数据
    async initData() {
      let { total, rows } = await getEmployeesListApi(this.queryData);
      this.total = total;
      this.list = rows;
    },
    // 【列表功能】 每页数量更换事件
    sizeChange(val) {
      this.queryData.size = val;
      this.initData();
    },
    // 【列表功能】 页码切换时间
    // currentChange(val) {
    //   this.queryData.page = val;
    //   this.initData();
    // },
    // 格式化聘用形式
    formatterEmployment(row, column, cellValue, index) {
      // row 是行的数据  column是列的信息， cellValue单元格数据 ， index是索引
      // console.log(row, column, cellValue, index);
      let result = this.hireType.find((item) => item.id === cellValue);
      return result ? result.value : "未知";
    },
    // 【删除功能】
    async delRow(id) {
      try {
        await this.$confirm("确认删除吗？");
      } catch (error) {
        return console.log(error);
      }
      await delEmployeesApi(id);
      this.$message.success("删除成功");
      if (this.list.length === 1 && this.queryData.page !== 1) {
        this.queryData.page--;
      }
      this.initData();
    },
    // 【导出功能】
    async exportAllData() {
      //  1. 获取到所有的数据
      let { rows } = await getEmployeesListApi({ page: 1, size: 1000000 });
      // 2.  整理数据
      let { headerKey, result } = this.formateData(rows);
      // 3. 调用插件导出数据
      // import('模块路径')  返回一个promise。  动态加载模块
      import("@/vendor/Export2Excel").then((excel) => {
        // excel 就是读取到的模块信息
        excel.export_json_to_excel({
          header: headerKey, //表头 必填
          data: result, //具体数据 必填
          filename: "员工数据", //文件名称
          autoWidth: true, //宽度是否自动
          bookType: "xlsx", //格式类型
        });
      });
    },
    // 整理数据
    formateData(row) {
      // 准备好表头
      const headers = {
        姓名: "username",
        手机号: "mobile",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };
      //results [{timeOfEntry:3222,username:'高大山',mobile:18868816112,correctionTime:43719},{...},{...}]
      //results [[3222,高大山,1886881611243719,],[3222,高大山,1886881611243719,],[],....]
      let result = [];
      let headerKey = Object.keys(headers);
      row.forEach((item) => {
        // item  {timeOfEntry:3222,username:'高大山',mobile:18868816112,correctionTime:43719}
        // Object.keys(headers)  [手机号,姓名,入职日期,聘用形式,转正日期,工号,部门]
        let temp = [];
        headerKey.forEach((name) => {
          // name 是中文键名    headers[name] 是英文  item[ headers[name] ] 英文键对应的数据
          // console.log(name, headers[name], item[headers[name]]);
          if (headers[name] === "formOfEmployment") {
            let findRes = this.hireType.find(
              (obj) => obj.id === item[headers[name]] * 1
            );
            let str = findRes ? findRes.value : "未知";
            temp.push(str);
          } else if (
            ["timeOfEntry", "correctionTime"].includes(headers[name])
          ) {
            temp.push(formatDate(item[headers[name]]));
          } else {
            temp.push(item[headers[name]]);
          }
        });
        result.push(temp);
      });
      return { headerKey, result };
    },
    // 调出选中的数据
    exportCheckData() {
      // 1. 准备数据
      // 2. 整理数据
      let { headerKey, result } = this.formateData(this.multipleSelection);
      //  3. 导出数据
      import("@/vendor/Export2Excel").then((excel) => {
        excel.export_json_to_excel({
          header: headerKey, // 正常表头
          multiHeader: [["姓名", "基本信息", "", "", "", "", "部门"]], //复杂表头
          merges: ["A1:A2", "B1:F1", "G1:G2"],
          data: result, //具体数据 必填
          filename: "员工数据-选中", //文件名称
          autoWidth: true, //宽度是否自动
          bookType: "xlsx", //格式类型
        });
      });
    },
    // 展示二维码
    showCodeImg(url) {
      if (!url.trim()) return this.$message.warning("没有头像");
      this.showCode = true; // 第一次弹框打开，内容的内容才开始创建。DOM的渲染是异步的
      // 等到DOM渲染完成之后执行
      this.$nextTick(() => {
        var canvas = this.$refs.canvas;
        console.log(canvas); // undefined
        // QRCode.toCanvas(画布位置，内容，回调函数)
        QRCode.toCanvas(canvas, url, function (error) {
          if (error) console.error(error);
          console.log("success!");
        });
      });
    },
    // 打开角色设置弹框
    async setRoleOpen(id) {
      // 请求改行员工的详细信息
      let { roleIds } = await getEmployeesInfoApi(id);
      this.$refs.setRole.checkRoleList = roleIds || [];
      this.$refs.setRole.userId = id;
      await this.$refs.setRole.getRoleList();
      this.$refs.setRole.showDialog = true;
    },
  },
};
</script>
<style lang="scss" scoped></style>
